<?php

namespace App\Imports;

use App\Models\Customer;
use App\Models\District;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class CustomerImport implements ToCollection
{

    public function collection(Collection $rows)
    {
        $userTexts = [];
        foreach ($rows as $key => $row) {
            if ($key == 0) {
                continue;
            }
            array_push($userTexts, $row[10]);
        }
        $users = User::whereIn('realname', $userTexts)->get();

        $data = [];
        foreach ($rows as $key => $row) {
            if ($key == 0) {
                continue;
            }
            $province = District::where('name', 'like', $row[7] .'%')->where('level', 1)->first();
            $city = District::where('name', 'like', $row[8].'%')->where('level', 2)->first();
            // 跟进人
            foreach ($users as $item) {
                if ($item->realname == $row[10]) {
                    $user = $item;
                }
            }
            array_push($data, [
                'from' => Customer::getFromValue($row[1]),
                'contact_name' => $row[4],
                'contact_mobile' => $row[5],
                'company_name' => $row[6] ?: '',
                'company_desc' => $row[11],
                'province' => $province ? $province->id : 0,
                'city' => $city ? $city->id : 0,
                'create_id' => get_user_id(),
                'follow_id' => $user ? $user->id : 0,
                'status' => Customer::STATUS_NORMAL,
                'remark' => '',
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ]);
        }

        Customer::insert($data);
    }
}
